package cn.hello2018.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author jeymingwu
 * @date 2019/3/11 10:27
 */
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 定位文件下载路径
        String path = getServletContext().getRealPath("/") + "images/";
        String filename = req.getParameter("filename");
        File file = new File(path + filename);
        if (file.exists()) {
            // 设置相应类型
            resp.setContentType("application/x-msdownload");
            // 设置头信息
            resp.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
            InputStream inputStream = new FileInputStream(file);
            ServletOutputStream outputStream = resp.getOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, n);
            }
            // 关闭流、释放资源
            inputStream.close();
            outputStream.close();
        } else {
            req.setAttribute("errorResult", "文件不存在，下载失败");
            req.setAttribute("path", path + filename);
            req.getRequestDispatcher("/jsp/uploadImage.jsp").forward(req, resp);
        }
    }
}
